//
//  IntervalTimerController.m
//  IntervalTimer
//
//

#import "IntervalTimerController.h"

@implementation IntervalTimerController


//TODO save defaults from last time

- (void) awakeFromNib {
//	[countdownDisplay setFont:[NSFont systemFontOfSize:80]];
//	[countdownDisplay setString:@"0"];
	nsTimer = nil;
	speechSynthesizer  = [NSSpeechSynthesizer new];
	if (speechSynthesizer == nil) {
		NSLog(@"Couldn't instantiate speech synthesizer.\n");
		exit(-1);
	}
	[speechSynthesizer setVoice:NULL]; //default voice
}

- (IBAction)startRunning:(id)sender {
	[stopButton setEnabled:YES];
	[startButton setEnabled:NO];
	//could potentially get into trouble if content ever changes.
    intervalTimer= [self content];
	//NSLog(@"start button got clicked!\n");
	currentSet = 1;
	currentState = WORK_STATE;
	
	/*
	NSLog(@"restmin = %d, workmin = %d, restsec = %d, worksec = %d, restint = %d, workint = %d\n", 
		  [intervalTimer restTimeMinutes], [intervalTimer workTimeMinutes], [intervalTimer restTimeSeconds], [intervalTimer workTimeSeconds],
		  [intervalTimer restInterval], [intervalTimer workInterval]);
	*/
	[self startOfWorkInterval:nil];
	secondsRemaining = [intervalTimer workInterval];
	nsTimer = [NSTimer scheduledTimerWithTimeInterval: 1
											   target: self
											 selector: @selector(updateCountdownDisplay:)
											 userInfo: nil
											  repeats: YES];
	
	
}


- (void) stopSpeaking {
	if([speechSynthesizer isSpeaking]) {
        [speechSynthesizer stopSpeaking];
    }
}

- (IBAction)stopRunning:(id)sender {
	
	NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
	[stopButton setEnabled:NO];
	[startButton setEnabled:YES];
	[nsTimer invalidate];
//	nsTimer = nil;
	[countdownDisplay setString: [NSString stringWithFormat:@"%d", [intervalTimer workInterval]]];
	currentState = WORK_STATE;
	secondsRemaining = 31337; //this shouldn't make a difference
	currentSet = 31337;
	[pool drain];
}

- (void) speakCurrentPhrase {
	NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
	NSString *currentPhrase = (currentState == REST_STATE) ? [intervalTimer restText] : [intervalTimer workText];
	
	//replace "$set" in the text with the set number
	NSMutableString *toSpeak = [NSMutableString stringWithString:currentPhrase];
	
	NSString *curSetString = [NSString stringWithFormat:@"%d", currentSet];
	[toSpeak replaceOccurrencesOfString:@"$set" 
							 withString: curSetString 
								options:0 
								  range: NSMakeRange(0, [toSpeak length])];
	[self stopSpeaking];
	[speechSynthesizer startSpeakingString:toSpeak];
	[pool drain];
}

- (void) startOfWorkInterval: (NSTimer *) timer {
	NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
	if (currentSet > [intervalTimer numSets]) {
		[self stopSpeaking];
		[speechSynthesizer startSpeakingString:@"You are done"];
		
		[self stopRunning:nil]; //cleanup everything, same as pressing the stop button.
		return;
	}
	NSString *curSetString = [NSString stringWithFormat:@"%d", currentSet];
	[currentSetDisplay setString:curSetString];
	[currentPhaseDisplay setStringValue:@"Work"];
	NSLog(@"start of work set %d interval = %d\n", currentSet, [intervalTimer workInterval]);
	[self speakCurrentPhrase];
	[pool drain];
	
}

- (void) startOfRestInterval: (NSTimer *) timer {
	
	NSLog(@"start of rest set %d interval = %d\n", currentSet, [intervalTimer restInterval]);
	[currentPhaseDisplay setStringValue:@"Rest"];
	[self speakCurrentPhrase];
}

- (int) currentInterval {
	return (currentState == REST_STATE) ? [intervalTimer restInterval] : [intervalTimer workInterval];
}

- (void) startOfCurrentInterval {
	(currentState == REST_STATE) ? [self startOfRestInterval:nil] : [self startOfWorkInterval:nil];
}

- (int) nextState {
	return (currentState == REST_STATE) ? WORK_STATE : REST_STATE;
}

- (void) updateCountdownDisplay:(NSTimer *) timer {	
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	
	secondsRemaining--;
	[countdownDisplay setString: [NSString stringWithFormat:@"%d", secondsRemaining]];
	
	if (secondsRemaining <= 0) {
		currentState = [self nextState]; //must do this first, since all the current* functions rely on it.

		if (currentState == WORK_STATE) {
			currentSet++;	
		}
		[countdownDisplay setString: [NSString stringWithFormat:@"%d", [self currentInterval]]];
		secondsRemaining = [self currentInterval];
		[self startOfCurrentInterval];
	} 
	[pool drain];
}

- (int) currentSet{
	return currentSet;
}
- (void) setCurrentSet: (int) val {
	currentSet = val;
}

-(void) dealloc {
	[intervalTimer release];
	[nsTimer release];
	[speechSynthesizer release];
	[super dealloc];
}
@end
